package com.summer.project.system.shoyo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.summer.common.utils.DateUtils;
import com.summer.common.utils.EmailUtils;
import com.summer.project.system.shoyo.domain.Good;
import com.summer.project.system.shoyo.service.IShoyoService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("shoyoService")
public class ShoyoServiceImpl implements IShoyoService {
    private static final Logger log = LoggerFactory.getLogger(ShoyoServiceImpl.class);

    @Value("${kai.shoyo.daily_path}")
    private String shoyoDailyPath;
    @Value("${kai.yujian.daily_path}")
    private String yujianDailyPath;

    @Value("${kai.shoyo.mobile}")
    private String shoyoMobile;
    @Value("${kai.shoyo.password}")
    private String shoyoPassword;


    @Value("${kai.yujian.mobile}")
    private String yujianMobile;
    @Value("${kai.yujian.password}")
    private String yujianPassword;

    @Value("${kai.receive_mail}")
    private String receiveMail;
    @Resource
    private EmailUtils emailUtils;

    private List<JSONObject> allIds = Lists.newArrayList();

    private DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
    private DateFormat df2 = new SimpleDateFormat("yyyy年MM月dd日");

    private String baseUrl = "https://bk.jbzyun.cn/micro/minipage?type=wpage&siteId={siteId}&limitNum=10&id=&storeId=&customPage=&middleId=&middlePageId=&version=0523";

    private String baseChildUrl = "https://bk.jbzyun.cn/micro/minipage?type=wpage&siteId={siteId}&limitNum=10&id={id}&storeId=&customPage=&middleId=&middlePageId=&version=0523";


    private String generateUrl = "https://bk.jbzyun.cn/micro/mall-extend/goods/generate-poster";


//    private String generateUrl = "https://bk.jbzyun.cn/micro/mall-extend/goods/getGoodsPosterTemplate";

    private String loginUrl = "https://bk.jbzyun.cn/micro/login/auth/login";
    private static CloseableHttpClient httpClient;

    static {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1800000)
                .setConnectionRequestTimeout(1800000)
                .setSocketTimeout(1800000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
                .setMaxConnTotal(1000)
                .setMaxConnPerRoute(1000)
                .build();
    }

    public void downByGoodId(String site, File dir, String token, String siteId, String agentId, Integer goodId) {
        try {
            log.info("==================开始执行《" + site + "》每日上架图片生成任务==================");
            this.getGoodListById(goodId, token, siteId, agentId, dir);
            if (dir.exists()) {
                File[] files = dir.listFiles();
                int maxAttachments = 50;

                if (files != null && files.length > 0) {
                    log.info("开始执行发送邮件任务！收件人：" + receiveMail);
                    List<String> paths = Lists.newArrayList();

                    for (File img : files) {
                        String absolutePath = img.getAbsolutePath();
                        paths.add(absolutePath);
                    }
                    int totalFiles = paths.size();
                    int numberOfEmails = (int) Math.ceil((double) totalFiles / maxAttachments);

                    for (int i = 0; i < numberOfEmails; i++) {
                        int start = i * maxAttachments;
                        int end = Math.min(start + maxAttachments, totalFiles);
                        List<String> subList = paths.subList(start, end);
                        String text = "附件请查收~";
                        if (!allIds.isEmpty()) {
                            text = text + "\n";
                            for (JSONObject json : allIds) {
                                Integer id = json.getInteger("id");
                                String name = json.getString("name");
                                text = text +id+"："+ name + "\n";
                            }
                        }
                        emailUtils.sendMessageWithMultipleAttachments(receiveMail, site + df2.format(new Date()) + "上架！", "附件请查收~", subList);
                        log.info("第 " + (i + 1) + " 封邮件发送完毕！");
                    }
                }
            }
            log.info("==================《" + site + "》每日上架图片生成任务完成！==================");
            System.out.println(allIds);
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            log.error(e.getMessage(), e);
            String exceptionText = sw.toString();
            String text = "\n\nException Message: " + e.getMessage() + "\n\nStack Trace:\n" + exceptionText;
            emailUtils.sendSimpleMessage(receiveMail, "生成图片错误！", "报错啦！\n" + text);
        }
    }


    @Override
    public void downByUrl(String url, String site) throws Exception {
        if (Objects.equals(site, "shoyo")) {
            String agentId = "168654126";
            String siteId = "9420";
            String token = this.login(shoyoMobile, shoyoPassword, siteId);

            List<Good> goodList = this.getGoodListByUrl(url, token, siteId, agentId);
            ;
            log.info("当前URL获取商品成功，共" + goodList.size() + "款商品");
            File baseDir = new File(shoyoDailyPath);
            if (!baseDir.exists()) {
                baseDir.mkdir();
            }
            log.info("开始生成图片");
            this.generateImage(agentId, goodList, token, Integer.parseInt(siteId));
            String today = df1.format(new Date());
            File dir = new File(shoyoDailyPath + File.separator + today + "ex");
            if (!dir.exists()) {
                dir.mkdirs();
            } else {
                deleteFiles(dir);
            }
            log.info("图片生成成功！");
            log.info("开始下载图片");
            for (int i = 0; i < goodList.size(); i++) {
                Good good = goodList.get(i);
                log.info("正在下载第" + (i + 1) + "张：" + good.getName());
                String imgUrl = good.getShareImgUrl();
                URL u = new URL(imgUrl);

                HttpsURLConnection conn = (HttpsURLConnection) u.openConnection();

                conn.setRequestProperty("connection", "keep-alive");
                conn.setRequestProperty("User-Agent", "Mozilla/4.76");

                DataInputStream dataInputStream = null;
                try {
                    dataInputStream = new DataInputStream(conn.getInputStream());
                } catch (Exception e) {
                    System.out.println("文件获取失败，继续下一个");
                    e.printStackTrace();
                    continue;
                }
                String name = good.getName().replace("\\", "").replace("/", "").replace("*", "").replace("：", "-").replace(":", "-");
                byte[] bytes = name.getBytes(); // 获取字节数组
                if (bytes.length > 200) { // 判断字节数是否超过200
                    byte[] truncatedBytes = new byte[200]; // 创建一个长度为200的字节数组
                    System.arraycopy(bytes, 0, truncatedBytes, 0, 200); // 复制前200个字节到新的数组
                    name = new String(truncatedBytes); // 将字节数组转换为字符串
                }
                FileOutputStream fileOutputStream = new FileOutputStream(dir.getAbsolutePath() + File.separator + i + name + ".jpg");
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = dataInputStream.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }
                fileOutputStream.write(output.toByteArray());
                dataInputStream.close();
                fileOutputStream.close();
            }

            File[] files = dir.listFiles();
            if (files != null && files.length > 0) {
                log.info("开始执行发送邮件任务！收件人：" + receiveMail);
                List<String> paths = Lists.newArrayList();
                for (File img : files) {
                    String absolutePath = img.getAbsolutePath();
                    paths.add(absolutePath);
                    if (paths.size() == 50) {
                        emailUtils.sendMessageWithMultipleAttachments(receiveMail, site + df2.format(new Date()) + "上架！", "附件请查收~", paths);
                        paths.clear();
                    }
                }
                if (!paths.isEmpty()) {
                    emailUtils.sendMessageWithMultipleAttachments(receiveMail, site + df2.format(new Date()) + "上架！", "附件请查收~", paths);
                }
                log.info("邮件发送完毕！");
            }
        }
        log.info("==================《" + site + "》手动URL图片生成任务完成！==================");

    }


    @Override
    public void downByChildUrl(String url, String site) throws Exception {
        if (Objects.equals(site, "shoyo")) {
            String agentId = "168654126";
            String siteId = "9420";
            String token = this.login(shoyoMobile, shoyoPassword, siteId);

            List<Good> goodList = this.getGoodList(url, token, siteId, agentId);
            log.info("当前URL获取商品成功，共" + goodList.size() + "款商品");
            File baseDir = new File(shoyoDailyPath);
            if (!baseDir.exists()) {
                baseDir.mkdir();
            }
            log.info("开始生成图片");
            this.generateImage(agentId, goodList, token, Integer.parseInt(siteId));
            String today = df1.format(new Date());
            File dir = new File(shoyoDailyPath + File.separator + today + "ex");
            if (!dir.exists()) {
                dir.mkdirs();
            } else {
                deleteFiles(dir);
            }
            log.info("图片生成成功！");
            log.info("开始下载图片");
            for (int i = 0; i < goodList.size(); i++) {
                Good good = goodList.get(i);
                log.info("正在下载第" + (i + 1) + "张：" + good.getName());
                String imgUrl = good.getShareImgUrl();
                URL u = new URL(imgUrl);

                HttpsURLConnection conn = (HttpsURLConnection) u.openConnection();

                conn.setRequestProperty("connection", "keep-alive");
                conn.setRequestProperty("User-Agent", "Mozilla/4.76");

                DataInputStream dataInputStream = null;
                try {
                    dataInputStream = new DataInputStream(conn.getInputStream());
                } catch (Exception e) {
                    System.out.println("文件获取失败，继续下一个");
                    e.printStackTrace();
                    continue;
                }
                String name = good.getName().replace("\\", "").replace("/", "").replace("*", "").replace("：", "-").replace(":", "-");
                byte[] bytes = name.getBytes(); // 获取字节数组
                if (bytes.length > 200) { // 判断字节数是否超过200
                    byte[] truncatedBytes = new byte[200]; // 创建一个长度为200的字节数组
                    System.arraycopy(bytes, 0, truncatedBytes, 0, 200); // 复制前200个字节到新的数组
                    name = new String(truncatedBytes); // 将字节数组转换为字符串
                }
                FileOutputStream fileOutputStream = new FileOutputStream(dir.getAbsolutePath() + File.separator + i + name + ".jpg");
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = dataInputStream.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }
                fileOutputStream.write(output.toByteArray());
                dataInputStream.close();
                fileOutputStream.close();
            }

            File[] files = dir.listFiles();
            if (files != null && files.length > 0) {
                log.info("开始执行发送邮件任务！收件人：" + receiveMail);
                List<String> paths = Lists.newArrayList();
                for (File img : files) {
                    String absolutePath = img.getAbsolutePath();
                    paths.add(absolutePath);
                    if (paths.size() == 50) {
                        emailUtils.sendMessageWithMultipleAttachments(receiveMail, site + df2.format(new Date()) + "上架！", "附件请查收~", paths);
                        paths.clear();
                    }
                }
                if (!paths.isEmpty()) {
                    emailUtils.sendMessageWithMultipleAttachments(receiveMail, site + df2.format(new Date()) + "上架！", "附件请查收~", paths);
                }
                log.info("邮件发送完毕！");
            }
        }
        log.info("==================《" + site + "》手动URL图片生成任务完成！==================");

    }


    @Override
    public void downShoyo() throws IOException {
        String site = "氧物派";
        String siteId = "9420";
        String token = this.login(shoyoMobile, shoyoPassword, siteId);
        String agentId = "168654126";
        File dir = this.getTodayDir(shoyoDailyPath);
        this.down(site, token, siteId, agentId, dir);
    }

    private File getTodayDir(String path) {
        File baseDir = new File(path);
        if (!baseDir.exists()) {
            baseDir.mkdir();
        }
        String today = df1.format(new Date());
        File dir = new File(path + File.separator + today);
        if (!dir.exists()) {
            dir.mkdirs();
        } else {
            deleteFiles(dir);
        }
        return dir;
    }

    private File geDirById(String path, Integer id) {
        File baseDir = new File(path);
        if (!baseDir.exists()) {
            baseDir.mkdir();
        }
        String today = df1.format(new Date());
        File dir = new File(path + File.separator + today + File.separator + id);
        if (!dir.exists()) {
            dir.mkdirs();
        } else {
            deleteFiles(dir);
        }
        return dir;
    }

    @Override
    public void downYujian() throws IOException {
        String site = "全球遇见";
        String siteId = "11232";
        String token = this.login(yujianMobile, yujianPassword, siteId);
        String agentId = "247215628";
        File dir = this.getTodayDir(yujianDailyPath);
        this.down(site, token, siteId, agentId, dir);
    }

    @Override
    public void downById(Integer id) throws IOException {
        String site = "氧物派";
        String siteId = "9420";
        String token = this.login(shoyoMobile, shoyoPassword, siteId);
        String agentId = "168654126";
        File dir = this.geDirById(shoyoDailyPath, id);
        this.downByGoodId(site, dir, token, siteId, agentId, id);
    }

    public void down(String site, String token, String siteId, String agentId, File dir) {
        String today = df1.format(new Date());
        try {
            log.info("==================开始执行《" + site + "》每日上架图片生成任务==================");
            this.downImg(siteId, dir, agentId, token);
            if (dir.exists()) {
                File[] files = dir.listFiles();
//                if (files != null && files.length > 0) {
//                    log.info("开始执行发送邮件任务！收件人：" + receiveMail);
//                    List<String> paths = Lists.newArrayList();
//                    for (File img : files) {
//                        String absolutePath = img.getAbsolutePath();
//                        paths.add(absolutePath);
//                    }
//                    emailUtils.sendMessageWithMultipleAttachments(receiveMail, site + df2.format(new Date()) + "上架！", "附件请查收~", paths);
//                    log.info("邮件发送完毕！");
//                }
                int maxAttachments = 50;

                if (files != null && files.length > 0) {
                    log.info("开始执行发送邮件任务！收件人：" + receiveMail);
                    List<String> paths = Lists.newArrayList();

                    for (File img : files) {
                        String absolutePath = img.getAbsolutePath();
                        paths.add(absolutePath);
                    }
                    int totalFiles = paths.size();
                    int numberOfEmails = (int) Math.ceil((double) totalFiles / maxAttachments);

                    for (int i = 0; i < numberOfEmails; i++) {
                        int start = i * maxAttachments;
                        int end = Math.min(start + maxAttachments, totalFiles);
                        List<String> subList = paths.subList(start, end);
                        String text = "附件请查收~\n\n";
                        if (!allIds.isEmpty()) {
                            text = text + "\n";
                            for (JSONObject json : allIds) {
                                Integer id = json.getInteger("id");
                                String name = json.getString("name");
//                                text = text +id+"："+ name + "\n";
                                // 添加超链接格式，使用示例链接并包含goodId参数
                                text = text + "<a href=\"http://nas.summor.cn:19999/kai/system/shoyo/down-by-id?id=" + id + "\">" + id + "：" + name + "</a><br/><br/>";

                            }
                        }
                        emailUtils.sendMessageWithMultipleAttachments(receiveMail, site + df2.format(new Date()) + "上架！", text, subList);
                        log.info("第 " + (i + 1) + " 封邮件发送完毕！");
                    }
                }
            }
            log.info("==================《" + site + "》每日上架图片生成任务完成！==================");
            System.out.println(allIds);
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            log.error(e.getMessage(), e);
            String exceptionText = sw.toString();
            String text = "\n\nException Message: " + e.getMessage() + "\n\nStack Trace:\n" + exceptionText;
            emailUtils.sendSimpleMessage(receiveMail, "生成图片错误！", "报错啦！\n" + text);
        }
    }


    public void downImg(String siteId, File dir, String agentId, String token) throws Exception {

        String minipageUrl = baseUrl.replace("{siteId}", siteId);
        log.info("获取今日上架商品");
        List<Good> goodList = getGoodListNew(minipageUrl, token, siteId, agentId);
        log.info("获取今日上架商品成功，今日共上架" + goodList.size() + "款商品");

        log.info("开始生成图片");
        this.generateImage(agentId, goodList, token, Integer.valueOf(siteId));

        log.info("图片生成成功！");
        log.info("开始下载图片");
        for (int i = 0; i < goodList.size(); i++) {
            Good good = goodList.get(i);
            log.info("正在下载第" + (i + 1) + "张：" + good.getName());
            String imgUrl = good.getShareImgUrl();
            try {
                URL u = new URL(imgUrl);

                HttpsURLConnection conn = (HttpsURLConnection) u.openConnection();

                conn.setRequestProperty("connection", "keep-alive");
                conn.setRequestProperty("User-Agent", "Mozilla/4.76");

                DataInputStream dataInputStream = null;
                try {
                    dataInputStream = new DataInputStream(conn.getInputStream());
                } catch (Exception e) {
                    System.out.println("文件获取失败，继续下一个");
                    e.printStackTrace();
                    continue;
                }
                String name = good.getName().replace("\\", "").replace("/", "").replace("*", "").replace("：", "-").replace(":", "-");
                byte[] bytes = name.getBytes(); // 获取字节数组
                if (bytes.length > 200) { // 判断字节数是否超过200
                    byte[] truncatedBytes = new byte[200]; // 创建一个长度为200的字节数组
                    System.arraycopy(bytes, 0, truncatedBytes, 0, 200); // 复制前200个字节到新的数组
                    name = new String(truncatedBytes); // 将字节数组转换为字符串
                }
                FileOutputStream fileOutputStream = new FileOutputStream(dir.getAbsolutePath() + File.separator + i + name + ".jpg");
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = dataInputStream.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }
                fileOutputStream.write(output.toByteArray());
                dataInputStream.close();
                fileOutputStream.close();
            } catch (Exception e) {
                System.out.println("文件【 " + good.getName() + " 】获取失败，继续下一个：");
                System.out.println("当前文件URL:---->" + good.getImgUrl());
            }
        }
        log.info("图片下载完成！");
    }

    private void getGoodListById(Integer id, String token, String siteId, String agentId, File dir) throws Exception {
        List<Good> goodList = Lists.newArrayList();
        if (id != null) {
            goodList.addAll(getGoods(id, token, String.valueOf(agentId)));
        }
        log.info("获取今日上架商品成功，今日共上架" + goodList.size() + "款商品");

        log.info("开始生成图片");
        this.generateImage(agentId, goodList, token, Integer.valueOf(siteId));

        log.info("图片生成成功！");
        log.info("开始下载图片");
        for (int i = 0; i < goodList.size(); i++) {
            Good good = goodList.get(i);
            log.info("正在下载第" + (i + 1) + "张：" + good.getName());
            String imgUrl = good.getShareImgUrl();
            try {
                URL u = new URL(imgUrl);

                HttpsURLConnection conn = (HttpsURLConnection) u.openConnection();

                conn.setRequestProperty("connection", "keep-alive");
                conn.setRequestProperty("User-Agent", "Mozilla/4.76");

                DataInputStream dataInputStream = null;
                try {
                    dataInputStream = new DataInputStream(conn.getInputStream());
                } catch (Exception e) {
                    System.out.println("文件获取失败，继续下一个");
                    e.printStackTrace();
                    continue;
                }
                String name = good.getName().replace("\\", "").replace("/", "").replace("*", "").replace("：", "-").replace(":", "-");
                byte[] bytes = name.getBytes(); // 获取字节数组
                if (bytes.length > 200) { // 判断字节数是否超过200
                    byte[] truncatedBytes = new byte[200]; // 创建一个长度为200的字节数组
                    System.arraycopy(bytes, 0, truncatedBytes, 0, 200); // 复制前200个字节到新的数组
                    name = new String(truncatedBytes); // 将字节数组转换为字符串
                }
                FileOutputStream fileOutputStream = new FileOutputStream(dir.getAbsolutePath() + File.separator + i + name + ".jpg");
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = dataInputStream.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }
                fileOutputStream.write(output.toByteArray());
                dataInputStream.close();
                fileOutputStream.close();
            } catch (Exception e) {
                System.out.println("文件【 " + good.getName() + " 】获取失败，继续下一个：");
                System.out.println("当前文件URL:---->" + good.getImgUrl());
            }
        }
        log.info("图片下载完成！");

    }

    private List<Good> getGoodListNew(String page, String token, String siteId, String agentId) throws Exception {
        String childPageUrl = baseChildUrl.replace("{siteId}", siteId);
        HttpGet get = new HttpGet(page);
        get.setHeader("Access-Control-Allow-Origin", "https://h5.jbzyun.cn");
        get.setHeader("X-C3-Agentid", String.valueOf(agentId));
        get.setHeader("X-C3-Token", token);
        get.setHeader("X-Client-Type", "h5");
        List<Good> goodList = Lists.newArrayList();
        List<Integer> childPageIds = Lists.newArrayList();
        HttpResponse response = httpClient.execute(get);
        List<Integer> ids = Lists.newArrayList();
        if (response != null && response.getEntity() != null) {
            String result = EntityUtils.toString(response.getEntity(), "UTf-8");
            JSONObject json = JSON.parseObject(result);
            JSONObject body = json.getJSONObject("body");
            JSONObject htmlPage = body.getJSONObject("htmlPage");
            JSONArray htmlBodys = htmlPage.getJSONArray("htmlBody");
            JSONObject daily = new JSONObject();
            daily.put("htmlBody", htmlBodys);
            daily.put("date", DateUtils.getNowDate());
            // 写入 htmlBody 到 daily.json 文件
            writeToJsonFile(daily);
//            JSONArray htmlBodys = JSON.parseArray(htmlBody);
            for (Object o : htmlBodys) {
                JSONObject html = (JSONObject) o;
                if (html.containsKey("activities")) {
                    JSONArray activities = html.getJSONArray("activities");
                    for (int i = 0; i < activities.size(); i++) {
                        JSONObject activity = activities.getJSONObject(i);
                        String name = activity.getString("name");
                        String startTime = activity.getString("startTime");
                        String endTime = activity.getString("endTime");
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        String start = df.format(DateUtils.getNowDate());
                        String end = df.format(DateUtils.addDays(DateUtils.getNowDate(), 2));
                        Integer id = activity.getInteger("id");
                        allIds.add(activity);
                        if ((startTime != null && startTime.contains(start)) || (endTime != null && endTime.contains(end))) {
                            System.out.println(name + ":" + id);
                            ids.add(id);
                        }
                    }
                }

//                    if (html.containsKey("goods") ) {
//                        JSONArray array = html.getJSONArray("goods");
//                        if (array == null) {
//                            continue;
//                        }
//                        for (int j = 0; j < array.size(); j++) {
//                            Good good = JSON.toJavaObject(array.getJSONObject(j), Good.class);
//                            if (html.getIntValue("uuid") == 529) {
//
//                                good.setActivityTemplateId(126876);
//                            } else if (html.getIntValue("uuid") == 730) {
//                                good.setActivityTemplateId(126670);
//                            }
//                            goodList.add(good);
//                        }
//                    }



//                JSONArray imageList = html.getJSONArray("imageList");
//                if (imageList != null && imageList.size() > 0) {
//                    imageList.forEach(i -> {
//                        JSONObject image = (JSONObject) i;
//                        JSONArray hotAreas = image.getJSONArray("hotAreas");
//                        if (hotAreas != null) {
//                            hotAreas.forEach(h -> {
//                                JSONObject hotArea = (JSONObject) h;
//                                JSONObject linkUrl = hotArea.getJSONObject("linkUrl");
//                                if (Objects.equals("100", hotArea.getString("widthRate")) && !Objects.equals(linkUrl.getString("title"), "轻氧专区") && linkUrl.getIntValue("id") != 0) {
//                                    childPageIds.add(linkUrl.getIntValue("id"));
//                                }
//                            });
//                        }
//                    });
//                }


            }
        }
//        ids.clear();
//        ids.add(167455 );
        if (!ids.isEmpty()) {
            for (Integer activityTemplateId : ids) {
                goodList.addAll(getGoods(activityTemplateId, token, String.valueOf(agentId)));
            }
        }
//        childPageIds.add(5341133);
//        if (!childPageIds.isEmpty()) {
//            for (Integer id : childPageIds) {
//                goodList.addAll(getGoodList(childPageUrl.replace("{id}", String.valueOf(id)), token, siteId, String.valueOf(agentId)));
//            }
//        }
        return goodList;
    }

    private void writeToJsonFile(Object content) {
        try {
            // 获取 resources 目录路径
            ClassLoader classLoader = getClass().getClassLoader();
            URL resource = classLoader.getResource("");
            if (resource != null) {
                String resourcesPath = resource.getPath();
                File jsonFile = new File(resourcesPath + "daily.json");
                if (!jsonFile.exists()) {
                    jsonFile.createNewFile();
                }
                try (FileWriter writer = new FileWriter(jsonFile)) {
                    writer.write(JSON.toJSONString(content));
                }
            }
        } catch (IOException e) {
            log.error("写入 daily.json 文件时出错", e);
        }
    }


    private List<Good> getGoods(int activityTemplateId, String token, String agentId) throws Exception {
        List<Good> goods = Lists.newArrayList();
        String pageUrl = "https://bk.jbzyun.cn/micro/marketing/limitDiscount/page?activityIds=" + activityTemplateId + "&scenario=ONGOING&pageNo=1&saleHours=999&pageSize=9999";
        HttpGet get = new HttpGet(pageUrl.replace("{id}", String.valueOf(activityTemplateId)));
        get.setHeader("Access-Control-Allow-Origin", "https://h5.jbzyun.cn");
        get.setHeader("X-C3-Agentid", agentId);
        get.setHeader("X-C3-Token", token);
        get.setHeader("X-Client-Type", "h5");
        HttpResponse goodResponse = httpClient.execute(get);
        if (goodResponse != null && goodResponse.getEntity() != null) {
            String result = EntityUtils.toString(goodResponse.getEntity(), "UTf-8");
            JSONObject json = JSON.parseObject(result);
            JSONArray bodies = json.getJSONArray("body");
            if (bodies == null) {
                return goods;
            }
            for (int i = 0; i < bodies.size(); i++) {
                JSONObject body = bodies.getJSONObject(i);
                if (body == null || !body.containsKey("goodsList")) {
                    continue;
                }
                JSONArray goodList = body.getJSONArray("goodsList");
                if (goodList == null) {
                    continue;
                }
                for (int j = 0; j < goodList.size(); j++) {
                    Good good = JSON.toJavaObject(goodList.getJSONObject(j), Good.class);
                    good.setActivityTemplateId(activityTemplateId);
                    goods.add(good);
                }
            }

        }
        return goods;
    }


    private List<Good> getGoodList(String page, String token, String siteId, String agentId) throws Exception {
        String childPageUrl = baseChildUrl.replace("{siteId}", siteId);
        HttpGet get = new HttpGet(page);
        get.setHeader("Access-Control-Allow-Origin", "https://h5.jbzyun.cn");
        get.setHeader("X-C3-Agentid", agentId);
        get.setHeader("X-C3-Token", token);
        get.setHeader("X-Client-Type", "h5");
        List<Good> goodList = Lists.newArrayList();
        List<Integer> childPageIds = Lists.newArrayList();
        HttpResponse response = httpClient.execute(get);
        if (response != null && response.getEntity() != null) {
            String result = EntityUtils.toString(response.getEntity(), "UTf-8");
            JSONObject json = JSON.parseObject(result);
            JSONObject body = json.getJSONObject("body");
            JSONObject htmlPage = body.getJSONObject("htmlPage");
            String htmlBody = htmlPage.getString("htmlBody");
            JSONArray htmlBodys = JSON.parseArray(htmlBody);
            for (Object o : htmlBodys) {
                JSONObject html = (JSONObject) o;
//                if (Objects.equals(html.getString("size"), "0")) {
                if (Objects.equals(html.getString("name"), "goods")) {
                    JSONArray goodArray = html.getJSONArray("goods");
                    for (Object obj : goodArray) {
                        Good good = JSON.toJavaObject(((JSONObject) obj), Good.class);
                        goodList.add(good);
                    }
                }
//                }
                JSONArray imageList = html.getJSONArray("imageList");
                if (imageList != null && imageList.size() > 0) {
                    imageList.forEach(i -> {
                        JSONObject image = (JSONObject) i;
                        JSONArray hotAreas = image.getJSONArray("hotAreas");
                        if (hotAreas != null) {
                            hotAreas.forEach(h -> {
                                JSONObject hotArea = (JSONObject) h;
                                JSONObject linkUrl = hotArea.getJSONObject("linkUrl");
                                if (Objects.equals("100", hotArea.getString("widthRate")) && !Objects.equals(linkUrl.getString("title"), "轻氧专区")) {
                                    childPageIds.add(linkUrl.getIntValue("id"));
                                }
                            });
                        }
                    });
                }

            }
        }
//        if (!childPageIds.isEmpty()) {
//            for (Integer id : childPageIds) {
//                goodList.addAll(getGoodList(childPageUrl.replace("{id}", String.valueOf(id)), token, siteId, agentId));
//            }
//        }
        return goodList;
    }

    private List<Good> getGoodListByUrl(String url, String token, String siteId, String agentId) throws Exception {
        HttpGet get = new HttpGet(url);
        String childPageUrl = baseChildUrl.replace("{siteId}", siteId);
        get.setHeader("Access-Control-Allow-Origin", "https://h5.jbzyun.cn");
        get.setHeader("X-C3-Agentid", agentId);
        get.setHeader("X-C3-Token", token);
        get.setHeader("X-Client-Type", "h5");
        List<Good> goodList = Lists.newArrayList();
        List<Integer> childPageIds = Lists.newArrayList();
        HttpResponse response = httpClient.execute(get);
        if (response != null && response.getEntity() != null) {
            String result = EntityUtils.toString(response.getEntity(), "UTf-8");
            JSONObject json = JSON.parseObject(result);
            JSONObject body = json.getJSONObject("body");
            JSONObject htmlPage = body.getJSONObject("htmlPage");
            String htmlBody = htmlPage.getString("htmlBody");
            JSONArray htmlBodys = JSON.parseArray(htmlBody);

            List<Integer> ids = Lists.newArrayList();

            for (Object o : htmlBodys) {
                JSONObject html = (JSONObject) o;
                if (html.containsKey("activities")) {
                    JSONArray activities = html.getJSONArray("activities");
                    for (int i = 0; i < activities.size(); i++) {
                        JSONObject activity = activities.getJSONObject(i);
                        String name = activity.getString("name");
                        String startTime = activity.getString("startTime");
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        String today = df.format(new Date());
                        if (startTime != null && startTime.contains(today)) {
                            Integer id = activity.getInteger("id");
                            System.out.println(name + ":" + id);
                            ids.add(id);
                        }
                    }
                }


                JSONArray imageList = html.getJSONArray("imageList");
                if (imageList != null && imageList.size() > 0) {
                    imageList.forEach(i -> {
                        JSONObject image = (JSONObject) i;
                        JSONArray hotAreas = image.getJSONArray("hotAreas");
                        if (hotAreas != null) {
                            hotAreas.forEach(h -> {
                                JSONObject hotArea = (JSONObject) h;
                                JSONObject linkUrl = hotArea.getJSONObject("linkUrl");
                                if (Objects.equals("100", hotArea.getString("widthRate")) && !Objects.equals(linkUrl.getString("title"), "轻氧专区")) {
                                    childPageIds.add(linkUrl.getIntValue("id"));
                                }
                            });
                        }
                    });
                }
            }
            if (!ids.isEmpty()) {
                for (Integer id : ids) {
                    goodList.addAll(getGoods(id, token, String.valueOf(agentId)));
                }
            }
            if (!childPageIds.isEmpty()) {
                for (Integer id : childPageIds) {
                    goodList.addAll(getGoodList(childPageUrl.replace("{id}", String.valueOf(id)), token, siteId, agentId));
                }
            }
        }

        return goodList;
    }


    private void generateImage(String agentId, List<Good> goodList, String token, Integer siteId) throws Exception {
        for (int i = 0; i < goodList.size(); i++) {
            Good good = goodList.get(i);
            log.info("正在生成第{}款商品：-> {}", i + 1, good.getName());
            // 生成小程序码
            HttpPost post = new HttpPost(generateUrl);
            if (good.getActivityTemplateId() != null && good.getActivityTemplateId() > 0) {
                post.setHeader("Access-Control-Allow-Origin", "https://h5.jbzyun.cn");

                post.setHeader("X-C3-Agentid", String.valueOf(agentId));
                post.setHeader("x-c3-mp-app", "wxa4c29ddfbe328619");
                post.setHeader("x-c3-site", String.valueOf(siteId));
                post.setHeader("x-c3-sjid", String.valueOf(siteId));
                post.setHeader("X-C3-Token", token);
                post.setHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.53(0x18003531) NetType/WIFI Language/zh_CN");
                post.setHeader("x-client-type", "mp");
                post.setHeader("agentId", String.valueOf(agentId));
                post.setHeader("sjid", String.valueOf(siteId));


                JSONObject reqParam = new JSONObject();
//            reqParam.put("type", "2");
                reqParam.put("numIid", String.valueOf(good.getId()));
                reqParam.put("storeId", "");
                reqParam.put("pageUrl", "pages/subPages/activeity/limitDiscount");
                reqParam.put("agentId", agentId);
                reqParam.put("scene", good.getId() + ";" + agentId + ";;;");
//            reqParam.put("scene", "goods;g-eOvBeJ5og-N7KDZv3tb");
                reqParam.put("activityTemplateId", good.getActivityTemplateId() == null ? "" : String.valueOf(good.getActivityTemplateId()));
                reqParam.put("activityType", "3");
                post.setEntity(new StringEntity(JSON.toJSONString(reqParam), ContentType.create(ContentType.APPLICATION_JSON.getMimeType(), "UTF-8")));
            } else {
                post.setHeader("Access-Control-Allow-Origin", "https://h5.jbzyun.cn");
                post.setHeader("X-C3-Agentid", String.valueOf(agentId));
                post.setHeader("X-C3-Token", token);
                post.setHeader("X-Client-Type", "mp");
                JSONObject reqParam = new JSONObject();
                reqParam.put("type", "2");
                reqParam.put("agentId", agentId);
                reqParam.put("numIid", String.valueOf(good.getId()));
                reqParam.put("scene", good.getId() + ";" + agentId + ";;;");
                reqParam.put("storeId", "");
                reqParam.put("activityTemplateId", "");
                reqParam.put("activityType", "");
                reqParam.put("pageUrl", "pagesB/main/goods/goodsDetail/index");
                post.setEntity(new StringEntity(JSON.toJSONString(reqParam), ContentType.create(ContentType.APPLICATION_JSON.getMimeType(), "UTF-8")));

            }








            HttpResponse httpResponse = httpClient.execute(post);
            // 获取结果实体
            HttpEntity responseEntity = httpResponse.getEntity();

            if (responseEntity != null) {
                // 按指定编码转换结果实体为String类型
                String res = EntityUtils.toString(responseEntity, "UTf-8");
//                System.out.println(res);
                JSONObject json = JSON.parseObject(res);
                if (Objects.equals(json.getString("code"), "401")) {
                    // 登录失败
                }
                JSONArray imgs = json.getJSONArray("body");
                if (imgs != null && imgs.size() > 0) {
                    good.setShareImgUrl(imgs.getString(0));
                }
            }
        }
    }

    private void deleteFiles(File folder) {
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteFiles(file);
                } else {
                    file.delete();
                }
            }
        }
    }

    private String login(String mobile, String password, String siteId) throws IOException {
        HttpPost post = new HttpPost(loginUrl);
        post.setHeader("Access-Control-Allow-Origin", "https://h5.jbzyun.cn");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("password", password));
        params.add(new BasicNameValuePair("mobile", mobile));
        params.add(new BasicNameValuePair("siteId", siteId));
        params.add(new BasicNameValuePair("loginType", "2"));
        // 添加更多参数，按需添加

        // 将参数设置到请求中
        post.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse httpResponse = httpClient.execute(post);
        HttpEntity responseEntity = httpResponse.getEntity();

        if (responseEntity != null) {
            // 按指定编码转换结果实体为String类型
            String res = EntityUtils.toString(responseEntity, "UTf-8");
            JSONObject json = JSON.parseObject(res);
            if (Objects.equals(json.getString("code"), "401")) {
                // 登录失败
            }
            JSONObject body = json.getJSONObject("body");
            return body.getString("token");
        }
        return "";
    }
}
